package com.bilgeadam.customtags;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 *
 * @author Bora SAYINER
 * @since Jan 18, 2015 6:41:41 PM
 * @version 1.0
 */
public class CustomTableTag extends SimpleTagSupport {

	private List<TableSupport> items;
	private String type;

	@Override
	public void doTag() throws JspException, IOException {
		StringBuilder stringBuilder = new StringBuilder();
		generateHeader(stringBuilder);
		generateBody(stringBuilder);
		getJspContext().getOut().print(stringBuilder.toString());
	}

	private void generateBody(StringBuilder stringBuilder) {
		try {
			Class<?> clazz = Class.forName(type);
			Method[] methods = clazz.getDeclaredMethods();
			stringBuilder.append("<tbody>");
			{
				for (Object item : items) {
					stringBuilder.append("<tr>");
					for (Method method : methods) {
						if (method.getName().startsWith("get") && !method.getName().equals("getColumnNames")) {
							Object value = method.invoke(item, null);
							stringBuilder.append("<td>" + value + "</td>");
						}
					}
					stringBuilder.append("</tr>");
				}
			}
			stringBuilder.append("</tbody>");
			stringBuilder.append("</table>");
		} catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	private void generateHeader(StringBuilder stringBuilder) {
		stringBuilder.append("<table border='1'>");
		{
			stringBuilder.append("<thead>");
			{
				stringBuilder.append("<tr>");
				{
					TableSupport tableSupport = items.get(0);
					for (String header : tableSupport.getColumnNames()) {
						stringBuilder.append("<th>" + header + "</th>");
					}
				}
				stringBuilder.append("</tr>");
			}
			stringBuilder.append("</thead>");
		}
	}

	public List<TableSupport> getItems() {
		return items;
	}

	public void setItems(List<TableSupport> items) {
		this.items = items;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}
